package com.topisv.tms.rest.qimen.util.delivery;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.qimen.DeliveryOrderTask;
import com.topisv.tms.rest.qimen.qmentity.ReceiverInfo;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorder.DeliveryOrder;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorder.DeliveryOrderItem;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorder.DeliveryOrderRequest;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorder.DeliveryRequirement;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorder.Insurance;
import com.topisv.tms.rest.qimen.qmentity.request.deliveryorder.Invoice;
import com.topisv.tms.rest.qimen.qmentity.request.stockout.StockOut;
import com.topisv.tms.rest.qimen.qmentity.request.stockout.StockOutItem;
import com.topisv.tms.rest.qimen.qmentity.request.stockout.StockOutRequest;
import com.topisv.tms.service.qimen.DeliveryOrderTaskService;
import com.topisv.tms.utils.WmsContants;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.utils.rule.TMSTransportRule;

public class TransferHelper {

	public static EdiOrder toEdiOrder(DeliveryOrderRequest request, DeliveryOrderTask task, Map<String, EdiGoodsSku> skuMap, Area area) {
		Date now = new Date();
		DeliveryOrder orderRequest = request.getDeliveryOrder();
		EdiOrder order = new EdiOrder();
		order.setStatus(StatusEnums.ORDERS_STSTUA_PENDING.getStatus());
		order.setOrderStatus(StatusEnums.ORDER_STATUS_OK.getStatus());
		order.setOrdeno(task.getOrderNo());
		order.setCustomerOrdeno(orderRequest.getDeliveryOrderCode());
		order.setDeliveryOrderType(orderRequest.getOrderType());
		order.setWarehouseCode(orderRequest.getWarehouseCode());
		order.setOrderFlag(orderRequest.getOrderFlag());
		order.setOrderFlag(orderRequest.getOrderFlag());
		order.setSourcePlatformCode(orderRequest.getSourcePlatformCode());
		order.setSourcePlatformName(orderRequest.getSourcePlatformName());
		order.setAdtime(orderRequest.getOperateTime());
		order.setCrtime(now);
		order.setPlaceOrderTime(orderRequest.getPlaceOrderTime());
		order.setPatime(orderRequest.getPayTime());
		order.setPayNo(orderRequest.getPayNo());
		order.setOutCreateTime(orderRequest.getCreateTime());
		order.setShopna(orderRequest.getShopNick());
		order.setShopCode(orderRequest.getShopNick());
		order.setBunick(orderRequest.getBuyerNick());
		order.setSellerNick(orderRequest.getSellerNick());
		order.setTotalAmount(orderRequest.getTotalAmount());
		order.setPodAmount(orderRequest.getServiceFee());
		order.setPosfee(orderRequest.getFreight());
		order.setCacode("null".equalsIgnoreCase(orderRequest.getLogisticsCode()) ? null : orderRequest.getLogisticsCode());
		order.setOldCacode(orderRequest.getLogisticsCode());
		order.setCaname(orderRequest.getLogisticsName());
		order.setMailNo(orderRequest.getExpressCode());
		order.setToShortAddress(orderRequest.getLogisticsAreaCode());
		order.setActuallyPaid(orderRequest.getArAmount());
		ReceiverInfo receiverInfo = orderRequest.getReceiverInfo();
		if(receiverInfo != null){
			order.setRecena(receiverInfo.getName());
			order.setPostco(receiverInfo.getZipCode());
			order.setProvna(receiverInfo.getProvince());
			order.setCityna(receiverInfo.getCity());
			order.setDistna(receiverInfo.getArea());
			order.setTown(receiverInfo.getTown());
			order.setTeleph(receiverInfo.getTel());
			order.setMobile(receiverInfo.getMobile());
			order.setAddres(receiverInfo.getDetailAddress());
			//详细地址里不包含省市的，拼接省市在地址里
			if (StringUtils.isNotBlank(receiverInfo.getDetailAddress()) && StringUtils.isNotBlank(receiverInfo.getProvince())) {
				if(receiverInfo.getDetailAddress().indexOf(receiverInfo.getProvince()) == -1){
					order.setAddres(new StringBuilder().append(receiverInfo.getProvince()).append(receiverInfo.getCity())
					    .append(receiverInfo.getArea()).append(receiverInfo.getTown()).append(receiverInfo.getDetailAddress()).toString());
				}
			}
		}
		
		order.setProvco(area != null ? area.getAreaCode() : null);
		
		List<Invoice> invoices = orderRequest.getInvoices();
		if (invoices != null) {
			for (Invoice invoice : invoices) {
				order.setInvoiceAmount(invoice.getAmount());
				order.setInvoiceTitle(invoice.getHeader());
				order.setInvoiceContent(invoice.getContent());
			}
		}
		
		Insurance insurance = orderRequest.getInsurance();
		if(insurance != null){
			order.setInsuranceType(insurance.getType());
			order.setInsuranceAmt(insurance.getAmount());
		}
		DeliveryRequirement deliveryRequirement = orderRequest.getDeliveryRequirement();
		if (deliveryRequirement != null) {
			order.setScheduleType(deliveryRequirement.getScheduleType());
			order.setScheduleDay(deliveryRequirement.getScheduleDay());
			order.setScheduleStartTime(deliveryRequirement.getScheduleStartTime());
			order.setScheduleEndTime(deliveryRequirement.getScheduleEndTime());
		}
		order.setIsUrgency(orderRequest.getIsUrgency());
		order.setIsInvoice(string2Boolean(orderRequest.getInvoiceFlag()));
		order.setBumemo(orderRequest.getBuyerMessage());
		order.setSememo(orderRequest.getSellerMessage());

		List<DeliveryOrderItem> itemsRequest = request.getDeliveryOrderItems();
		if (itemsRequest != null) {
			order.setOrderType(itemsRequest.size() > 1 ? StatusEnums.ORDER_TYPE_MULTIPLE.getStatus() : StatusEnums.ORDER_TYPE_SINGLE.getStatus());
			List<EdiOrderItem> orderItems = new ArrayList<EdiOrderItem>();
			List<String>  match = new ArrayList<String>();
			for (DeliveryOrderItem deliveryOrderItem : itemsRequest) {
				EdiOrderItem item = new EdiOrderItem();
				item.setSourceOrderCode(deliveryOrderItem.getSourceOrderCode());
				item.setSubSourceOrderCode(deliveryOrderItem.getSubSourceOrderCode());
				item.setExtCode(deliveryOrderItem.getExtCode());
				item.setNam(deliveryOrderItem.getItemName());
				item.setQty(deliveryOrderItem.getPlanQty());
				item.setAmo(deliveryOrderItem.getActualPrice());
				item.setDis(deliveryOrderItem.getDiscountAmount());
				item.setPri(deliveryOrderItem.getActualPrice());
				item.setSku(skuMap.get(deliveryOrderItem.getItemCode()).getSku());
				item.setLineNo(deliveryOrderItem.getOrderLineNo());
				order.setCustomerCode(deliveryOrderItem.getOwnerCode());
				order.setFromno(deliveryOrderItem.getSourceOrderCode());
				orderItems.add(item);
				//add by yanlei 判断订单结构
				if(!match.contains(item.getSku()))
				{
					match.add(item.getSku());
				}
			}
			//add by yanlei 判断订单结构
			order.setSkuMatch(match.size()==1 ? "1":"2");
			StringBuilder strbuild = new StringBuilder();
			order.setCheckRepeat(strbuild.append(order.getCustomerCode()).append(orderRequest.getDeliveryOrderCode()).toString());
			order.setSkulst(orderItems);
			order.setOrderItems(orderItems);
		}
		return order;
	}
	
	public static EdiOrder stockOuttoEdiOrder(StockOutRequest request, Map<String, EdiGoodsSku> skuMap) {
		Date now = new Date();
		StockOut orderRequest = request.getStockOut();
		EdiOrder order = new EdiOrder();
		order.setStatus(StatusEnums.ORDERS_STSTUA_PENDING.getStatus());
		order.setOrderStatus(StatusEnums.ORDER_STATUS_OK.getStatus());
		order.setOrdeno(TMSTransportRule.generateULBillCode());
		order.setCustomerOrdeno(orderRequest.getDeliveryOrderCode());
		order.setDeliveryOrderType(orderRequest.getOrderType());
		order.setWarehouseCode(orderRequest.getWarehouseCode());
		order.setCrtime(now);
		
		order.setCacode("null".equalsIgnoreCase(orderRequest.getLogisticsCode()) ? null : orderRequest.getLogisticsCode());
		order.setOldCacode(orderRequest.getLogisticsCode());
		order.setCaname(orderRequest.getLogisticsName());
		
		ReceiverInfo receiverInfo = orderRequest.getReceiverInfo();
		if(receiverInfo != null){
			order.setRecena(receiverInfo.getName());
			order.setPostco(receiverInfo.getZipCode());
			order.setProvna(receiverInfo.getProvince());
			order.setCityna(receiverInfo.getCity());
			order.setDistna(receiverInfo.getArea());
			order.setTown(receiverInfo.getTown());
			order.setTeleph(receiverInfo.getTel());
			order.setMobile(receiverInfo.getMobile());
			order.setAddres(receiverInfo.getDetailAddress());
			//详细地址里不包含省市的，拼接省市在地址里
			if (StringUtils.isNotBlank(receiverInfo.getDetailAddress()) && StringUtils.isNotBlank(receiverInfo.getProvince())) {
				if(receiverInfo.getDetailAddress().indexOf(receiverInfo.getProvince()) == -1){
					order.setAddres(new StringBuilder().append(receiverInfo.getProvince()).append(receiverInfo.getCity()).append(receiverInfo.getArea()).append(receiverInfo.getDetailAddress()).toString());
				}
			}
		}
		
		List<StockOutItem> items = request.getStockOutItems();
		if (items != null) {
			order.setOrderType(items.size() > 1 ? StatusEnums.ORDER_TYPE_MULTIPLE.getStatus() : StatusEnums.ORDER_TYPE_SINGLE.getStatus());
			List<EdiOrderItem> orderItems = new ArrayList<EdiOrderItem>();
			for (StockOutItem stockOutItem : items) {
				EdiOrderItem item = new EdiOrderItem();
				
				item.setNam(stockOutItem.getItemName());
				item.setQty(stockOutItem.getPlanQty());
				item.setOidStatus(("ZP".equals(stockOutItem.getInventoryType())||StringUtils.isBlank(stockOutItem.getInventoryType()))?"normal":stockOutItem.getInventoryType());
				item.setSku(skuMap.get(stockOutItem.getItemCode()).getSku());
				item.setLineNo(stockOutItem.getOrderLineNo());
				order.setCustomerCode(stockOutItem.getOwnerCode());
				
				orderItems.add(item);
			}
			order.setSkulst(orderItems);
			order.setOrderItems(orderItems);
		}
		return order;
	}

	public static boolean string2Boolean(String s) {
		return WmsContants.YES.equalsIgnoreCase(s) || "1".equals(s) ? true : false;
	}
}
